#include "InSdkG711Code.h"

#define MAX (32635)
unsigned char InSdk_G711_Encode(short pcm)
{
    int sign = (pcm & 0x8000) >> 8;
    if (sign != 0)
        pcm = -pcm;
    if (pcm > MAX) pcm = MAX;
    int exponent = 7;
    int expMask;
    for (expMask = 0x4000; (pcm & expMask) == 0 && exponent > 0; exponent--, expMask >>= 1)
    {
    }
    int mantissa = (pcm >> ((exponent == 0) ? 4 : (exponent + 3))) & 0x0f;
    unsigned char alaw = (unsigned char)(sign | exponent << 4 | mantissa);
    return (unsigned char)(alaw^0xD5);
}

short InSdk_G711_Decode(unsigned char alaw)
{
    alaw ^= 0xD5;
    int sign = alaw & 0x80;
    int exponent = (alaw & 0x70) >> 4;
    int data = alaw & 0x0f;
    data <<= 4;
    data += 8;
    if (exponent != 0)
        data += 0x100;
    if (exponent > 1)
        data <<= (exponent - 1);

    return (short)(sign == 0 ? data : -data);
}

/** 编码 **/
int Ext_InSdk_G711A_EnCode(char* pCodecBits, const char* pBuffer, int nBufferSize)
{
    int i;
    short* buffer = (short*)pBuffer;
    for(i=0; i<nBufferSize/2; i++)
    {
        pCodecBits[i] = InSdk_G711_Encode(buffer[i]);
    }

    return nBufferSize/2;
}

/** 解码 **/
int Ext_InSdk_G711A_Decode(char* pRawData, const  char* pBuffer, int nBufferSize)
{
    int i;
    short *out_data = (short*)pRawData;
    for(i=0; i<nBufferSize; i++)
    {
        out_data[i] = InSdk_G711_Decode(pBuffer[i]);
    }

    return nBufferSize*2;
}
